// pages/goods_detail/goods_detail.js
const app = getApp()
const db = wx.cloud.database()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    goods_info: '',
    _id:'',
    goods_kinds: [
      '/images/purchase/spot_goods.png',
      '/images/purchase/forward.png',
     ],
     total_price: 0,
  },


  // 下单跳转到订单页面
  createOrder: function(e){
    let that = this
    wx.switchTab({
      url: '/pages/orders/orders',
    })

    db.collection('order').add({
      // data 字段表示需新增的 JSON 数据
      data: {
        img_url: that.data.goods_info.img_url,
        title: that.data.goods_info.title,
        price: that.data.goods_info.price,
        num: that.data.goods_info.num,
        detail_kind: that.data.goods_info.detail_kind,
        total_price: parseInt(that.data.goods_info.num) * parseFloat(that.data.goods_info.price),
        order_rate: 10, 
        create_time: new Date(),
      }
    })
  },

  // 下单跳转到订单页面
  createPoster: function(){
    let that = this;
    let poster_info = {
      _id: that.data.goods_info._id,
      img_url: that.data.goods_info.img_url,
      title:  that.data.goods_info.title,
      detail: that.data.goods_info.detail,
      price: that.data.goods_info.price,
      phone: that.data.goods_info.phone,
    };

    wx.navigateTo({
      url: "/pages/poster/poster?poster_info=" + JSON.stringify(poster_info)
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({
      _id: options.id,
    })

    db.collection('goods').doc(options.id).get({
      success: function(res) {
        // res.data 包含该记录的数据
        that.setData({
          goods_info: res.data, 
        });

        if(that.data.goods_info.img_url){
          that.loadImage();
        }
      },
    })
  },


  loadImage: function () {
    var that = this;

    wx.cloud.downloadFile({
      fileID: that.data.goods_info.img_url, // 文件 ID
 
      success: function (res) {
        // 返回临时文件路径
        that.setData({
          image: res.tempFilePath
        })
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
